'use strict'

module.exports = core

const { homedir } = require('os')
const path = require('path')
const semver = require('semver')
const colors = require('colors/safe')
const pathExists = require('path-exists')
const dotenv = require('dotenv')
const commander = require('commander')
const log = require('@imooc-yishen-cli-dev/log')
const init = require('@imooc-yishen-cli-dev/init')
const exec = require('@imooc-yishen-cli-dev/exec')
const pkg = require('../package.json')
const constant = require('./const')

const program = new commander.Command()

async function core() {
  try {
    prepare()
    registerCommand()
  } catch (error) {
    log.error(error.message)
    if (program.debug) {
      console.log(e)
    }
  }
}

function registerCommand() {
  program
    .command('init [projectName]')
    .option('-f --force', '是否强制初始化项目,若本地存在将覆盖')
    .description('初始化项目')
    .action(exec)

  program
    .name(Object.keys(pkg.bin)[0])
    .usage('<command> [options]')
    .version(pkg.version)
    .option('-d --debug', 'whether to turn on debug mode', false)
    .option('-tp --targetPath <targetPath>', '是否指定本地调试文件路径', '')

  program.on('option:targetPath', () => {
    process.env.CLI_TARGET_PATH = program.opts().targetPath
  })

  // turn on debug mode
  program.on('option:debug', () => {
    if (program.opts().debug) {
      process.env.LOG_LEVEL = 'verbose'
    } else {
      process.env.LOG_LEVEL = 'info'
    }
    log.level = process.env.LOG_LEVEL
  })

  // not hit all command above，which listen unknown command
  program.on('command:*', (obj) => {
    console.log(colors.red('未知的命令', obj[0]))
    const availableCommands = program.commands.map((cmd) => cmd.name())
    console.log('可用命令：', availableCommands.join(','))
  })

  program.parse()

  if (program.args && program.args.length < 1) {
    program.outputHelp()
  }
}

async function prepare() {
  checkPkgVersion()
  checkRoot()
  checkUserHome()
  checkEnv()
  await checkGlobalUpdate()
}

async function checkGlobalUpdate() {
  const currentVersion = pkg.version
  const npmName = pkg.name
  const { getNpmSemverVersion } = require('@imooc-yishen-cli-dev/get-npm-info')
  const lastVersion = await getNpmSemverVersion(currentVersion, npmName)
  if (lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn(
      '更新提示',
      colors.yellow(
        `请手动更新 ${npmName} 当前版本 ${currentVersion} 最新版本 ${lastVersion}
        更新命令 npm install ${npmName}`
      )
    )
  }
}

function checkEnv() {
  const dotenvPath = path.resolve(process.env.OLDPWD, '.env')
  if (pathExists.sync(dotenvPath)) {
    dotenv.config({
      path: dotenvPath,
    })
  } else {
    createDefaultConfig()
  }
  log.verbose('环境变量', process.env.CLI_HOME_PATH)
}

function createDefaultConfig() {
  const cliConfig = {
    home: homedir(),
  }
  if (process.env.CLI_HOME) {
    cliConfig['cliHome'] = path.join(homedir(), process.env.CLI_HOME)
  } else {
    cliConfig['cliHome'] = path.join(homedir(), constant.DEFAULT_CLI)
  }
  process.env.CLI_HOME_PATH = cliConfig.cliHome
}

function checkUserHome() {
  if (!homedir() || !pathExists.sync(homedir())) {
    throw new Error(colors.red('当前用户主目录不存在！'))
  }
}

function checkPkgVersion() {
  log.notice('cli-version', pkg.version)
}

function checkRoot() {
  const rootCheck = require('root-check')
  rootCheck()
}
